<?php


namespace App\Services\Tools;


use App\Exceptions\BasicException;
use GuzzleHttp\Exception\RequestException;

class FrontHttpRequest
{
    //第三方请求状态
    const OUT_API_TYPE_SUCCESS  = 0; //第三方服务请求成功
    const OUT_API_TYPE_ERROR    = 1; //第三方服务请求失败
    const OUT_API_TYPE_TIME_OUT = 2; //第三方服务请求超时

    /**
     * 请求方式
     */
    const GET  = 'GET';
    const POST = 'POST';
    const DEL  = 'DELETE';
    const PUT  = 'PUT';

    private $httpClient;

    private $timeOutSecond = 5;//一个请求最大请求时长（超时时间）
    private $host;

    public function __construct()
    {
        $this->host = env('REPORT_URL', '');
        $sign = env('OUT_APP_SIGN', '');
        if (empty($this->host) || empty($sign)) {
            throw new BasicException(10010, '配置错误');
        }
        $this->httpClient = new \GuzzleHttp\Client([
            'base_uri' => $this->host, 'timeout' => $this->timeOutSecond, 'headers' => [
                'sign' => $sign,
            ],
        ]);
    }

    private function recordFileLog($method, $url, $httpStatusCode, $params = [])
    {

        return true;
    }

    /**
     * Desc: 发送同步请求 并纪录日志
     * User: XiaoSC
     *
     * @param $method  string GET POST PUT DELETE
     * @param $path string 除去域名后的路径
     * @param $params array 参数
     * @param $isThrow bool 是否抛出异常
     * @return ['type(0：对方业务成功 1：http错误或对方业务错误  2：http超时)' => 0, 'data（业务成功时返回业务数据）' => $res['data'], 'msg（错误信息）' => '']
     */
    private function request($method, $path, $params = [], $isThrow = true)
    {
        try {
            $res = $this->httpClient->request($method, $path, $params);
        } catch (RequestException $e) {
//            echo $e->getRequest();
            if ($e->hasResponse()) {
                if ($isThrow) {
                    throw new BasicException(10010, $e->getResponse());
                }
                return ['type' => self::OUT_API_TYPE_ERROR, 'data' => [], 'msg' => '与第三方服务交互失败'];
            }
        }

        $res = json_decode($res->getBody(), true);
        if (isset($res['code']) && $res['code']!=200) {//对方业务代码抛错
            if ($isThrow) {
                throw new BasicException(10010, $res['message']);
            } else {
                return ['type' => self::OUT_API_TYPE_SUCCESS, 'data' => [], 'msg' => $res['message']];
            }
        }

        return ['type' => 0, 'data' => $res['data'], 'msg' => ''];
    }

    /**
     * Desc: 上报用户信息
     * User: XiaoSC
     * Date: 2022/6/21 17:34
     * APP_Versions: 对接第三方渠道系统
     *
     * @param $params
     * @return array|bool
     * @throws BasicException
     */
    public function reportUserInfo($params)
    {
        $path = '/api/third/promote/user/info';
        if (empty($params['user_id'])) {
            return false;
        }
        if (empty($params['user_code'])) {
            unset($params['user_code']);
        }
        if (empty($params['nickname'])) {
            unset($params['nickname']);
        }
        if (empty($params['mobile'])) {
            unset($params['mobile']);
        }

        if (empty($params['is_shumei_black'])) {
            unset($params['is_shumei_black']);
        }
        if (count($params) == 1) {
            return false;
        }

        $params = ['form_params' => $params];//表单方式提交
        return $this->request(self::POST, $path, $params, true);
    }


    /**
     * Desc: 封禁房间
     * User: XiaoSC
     * Date: 2022/6/21 17:34
     * APP_Versions: qpyf1.4.7
     *
     * @param $params
     * @return array|bool
     * @throws BasicException
     */
    public function sealRoom($params)
    {
        $path = 'api/third/room/seal';
        if (empty($params['room_id'])) {
            return false;
        }
        $params = ['form_params' => $params];//表单方式提交
        $res = $this->request(self::POST, $path, $params, true);

        return $res;
    }

}